package com.xqx.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * @author：xingquanxiang createTime：2019/10/23 16:36
 * description:
 */
// @Component
public class ExceptionWriteUtil implements HandlerExceptionResolver {
    @Autowired
    @Qualifier("logWriter")
    private BufferedWriter logWriter;

    @Autowired
    @Qualifier("formatDate")
    private SimpleDateFormat formatDate;

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {

        if (e instanceof Exception) {
            try {
                StackTraceElement[] stackTrace = e.getStackTrace();
                String appendExceptionTime = formatDate.format(System.currentTimeMillis());
                /*for (StackTraceElement element : stackTrace) {
                    System.out.println("element = " + element);*/
                logWriter.write(new StringBuilder().append(appendExceptionTime).append(":").append(e.getMessage()).append("    class:").
                        append(e.getStackTrace()[0].getClassName()).append("    method:").append(e.getStackTrace()[0].getMethodName()).toString());
                logWriter.newLine();
                logWriter.write(new StringBuilder().append("    ").append(e.getStackTrace()[0].toString()).toString());
                logWriter.newLine();
                /*}*/
                logWriter.flush();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        //开发时将异常信息显示到控制台
        e.printStackTrace();
        //创建视图
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error");
        return modelAndView;
    }
}
